package com.micai.boss.base.oss;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/23 14:41
 */
public class RiskAliOssClient extends AbstractAliOssClient {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public RiskAliOssClient(String bucketName, String endpoint, String accessKeyId, String accessKeySecret) {
        super(bucketName, endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 得到风控图片文件
     *
     * @param key
     * @return
     */
    public File getRiskImageFile(String key) {
        InputStream inputStream = getInputStream(key);
        if (inputStream == null) {
            logger.error("获取oss认证图片为空 key{} bucket{}", key);
            return null;
        }
        String fileName = key.substring(key.lastIndexOf("/") + 1);
        int lastIndexOf = fileName.lastIndexOf(".");
        String prefix = null;
        String suffix = null;
        if (lastIndexOf == -1) {
            prefix = fileName;
            suffix = "";
        } else {
            prefix = fileName.substring(0, fileName.lastIndexOf("."));
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        return getFilebyInputStream(inputStream, prefix, suffix);
    }

    private static File getFilebyInputStream(InputStream inputStream, String prefix, String suffix) {
        File file = null;
        try {
            file = File.createTempFile(prefix, suffix);
            file.deleteOnExit();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int end = 0;
            while ((end = inputStream.read(b, 0, 1024)) != -1) {
                outputStream.write(b, 0, end);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
